package com.weibo.survey.controller;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.weibo.survey.domain.User;
import com.weibo.survey.service.UserService;
import com.weibo.survey.utils.DataUtils;

@Controller("registerAction")
@Scope("prototype")
public class RegisterAction extends BaseAction<User> {
	private static final long serialVersionUID = 2646991024817815539L;
	private static final String REGISTER = "register";
	private String confirm;
	@Resource(name = "userService")
	private UserService userService;

	@SkipValidation
	public String regPage() {
		return REGISTER;
	}

	public String doReg() {
		model.setPassword(DataUtils.md5(model.getPassword()));
		userService.saveEntity(model);
		return SUCCESS;
	}

	@Override
	public void validate() {
		if (StringUtils.isBlank(model.getEmail())) {
			addFieldError("email", "邮箱不能为空");
		} else {
			if (userService.isRegister(model.getEmail())) {
				addFieldError("email", "该邮箱已注册，请重新填写邮箱地址");
			}
		}
		if (StringUtils.isBlank(model.getPassword())) {
			addFieldError("password", "密码不能为空");
		} else if (model.getPassword().length() < 6) {
			addFieldError("password", "密码长度至少为6");
		}

		if (StringUtils.isBlank(confirm)) {
			addFieldError("confirm", "确认密码不能为空");
		} else if (!confirm.equals(model.getPassword())) {
			addFieldError("confirm", "确认密码必须与密码相同！");
		}

		if (StringUtils.isBlank(model.getNickname())) {
			addFieldError("nickname", "昵称不能为空");
		}
	}

	public String getConfirm() {
		return confirm;
	}

	public void setConfirm(String confirm) {
		this.confirm = confirm;
	}
}
